package sh.wn36.vehiclemanage.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import sh.wn36.vehiclemanage.entity.Dictionary;
import sh.wn36.vehiclemanage.entity.QUsers;
import sh.wn36.vehiclemanage.entity.dto.UserQuery;
import sh.wn36.vehiclemanage.entity.qz_entity.Login;
import sh.wn36.vehiclemanage.entity.qz_entity.UserPassword;
import sh.wn36.vehiclemanage.entity.qz_entity.Users;
import sh.wn36.vehiclemanage.service.DictionaryService;
import sh.wn36.vehiclemanage.service.QUsersService;
import sh.wn36.vehiclemanage.service.SelectQUsersService;
import sh.wn36.vehiclemanage.util.MD5Util;
import sh.wn36.vehiclemanage.util.Result;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xk
 * @since 2021-04-26
 */
@CrossOrigin
@Api(value = "用户管理 + 临时用户登录")
@RestController
@RequestMapping("/user")
public class QUsersController {
    @Autowired
    @ApiModelProperty("用户业务接口成员变量")
    private QUsersService usersService;
    @Autowired
    @ApiModelProperty("只用于查询封装的业务接口")
    private SelectQUsersService selectQUsersService;


    @Autowired
    @ApiModelProperty("部门服务接口")
    private DictionaryService dictionaryService;

    @ApiModelProperty("登录验证")
    @PostMapping("/login")
    public Result doUserLogin(@ApiParam(value = "用户名", name = "user", required = true) @RequestBody(required = false) Login user) {
        System.out.println(user.toString());
        QUsers users = usersService.loginUser(user.getUsername());
        if (users != null) {
            String s = MD5Util.md5Encrypt32Lower(user.getPassword());
            boolean equals = users.getLpass().equals(s);
            if (equals) {
                return Result.OK().data("token", user.getUsername());
            }
        }
        //-- token应该使用JWT技术生成
        return Result.Fail().data("token", null);
    }

    @ApiModelProperty("登录验证成功后获取token")
    @GetMapping("/info")
    public Result getUserInfo(@ApiParam(value = "用户名", name = "token", required = true) @RequestParam(required = false) String token) {
//        System.out.println("token"+token);
        if (token != null) {

            return Result.OK().data("roles", "user").data("name", token).data("avatar", "https://woniumd.oss-cn-hangzhou.aliyuncs.com/java/panweijun/20210420154958.jpg");
        }
        //-- 参考前端   k15_back\\src\\store\\modules\\user.js参考这里的内容
        return Result.OK();
    }

    @ApiModelProperty("退出登录让token为空值")
    @PostMapping("/logout")
    public Result getUserInfo() {
        return Result.OK().data("token", null);
    }

    @ApiModelProperty("修改密码")
    @PostMapping("/updatePassword")
    public Result updatePassword(@ApiParam(value = "用户密码对象", name = "lpass", required = true) @RequestBody(required = false) UserPassword  userPassword,
                                 @ApiParam(value = "用户密码对象", name = "X-Token", required = true) @RequestHeader("X-Token") String  token) {
        System.out.println("lpass"+userPassword);
        System.out.println("token"+token);
        QUsers users = usersService.loginUser(token);
        System.out.println("通过");
        String s = MD5Util.md5Encrypt32Lower(userPassword.getLpass());
        if (s.equals(users.getLpass())) {
            boolean b = usersService.updatePassword(users.getId(), userPassword.getRpass());
            if (b) {
                return Result.OK();
            }
        }
        return Result.Fail();


    }


    @RequestMapping("/usersList")
    @ApiModelProperty("查询出所有的用户信息")
    public Result UsersList() {
        List<QUsers> usersList = usersService.list();
        List<Users> users = new ArrayList<>();
        for (QUsers qUsers : usersList) {
//  同过用户的职位id查询出职位详细信息
            Dictionary position = dictionaryService.getById(qUsers.getPostid());
            //            获取用户的部门编号 和名称
            Dictionary department = dictionaryService.getById(position.getPid());
            Users users1 = new Users();
            users1.setAddress(qUsers.getAddress());
            users1.setLname(qUsers.getLname());
            ;
            users1.setId(qUsers.getId());
            users1.setLpass(qUsers.getLpass());
            users1.setRname(qUsers.getRname());
            users1.setAge(qUsers.getAge());
            users1.setPhone(qUsers.getPhone());
            users1.setDepartment(department.getText());
            users1.setPosition(position.getText());
            users1.setBirthday(qUsers.getBirthday());
            users1.setCard(qUsers.getCard());
            users1.setEntrytime(qUsers.getEntrytime());
            users1.setIsdisable(qUsers.getIsdisable() == 1 ? "启用" : "禁用");
            users1.setVersion(qUsers.getVersion());
            users1.setGmtCreate(qUsers.getGmtCreate());
            users1.setGmtModified(qUsers.getGmtModified());
            users.add(users1);
        }
        System.out.println("封装好的用户集合" + users);

        if (users != null) {
            return Result.OK();
        }
        return Result.Fail();

    }


    @PostMapping("/updateUser")
    @ApiOperation(value = "修改用户")
    public Result updateUser(@RequestBody QUsers users) {
        boolean result = usersService.updateById(users);
        if (result)
            return Result.OK();
        else
            return Result.Fail();
    }


    @ApiModelProperty(value = "添加用户")
    @PostMapping("/saveUser")
    public Result addUser(@RequestBody QUsers users) {

        boolean result = usersService.save(users);
        if (result) {
            return Result.OK();
        } else {
            return Result.Fail();
        }

    }

    @ApiModelProperty("根据用户ID删除用户")
    @GetMapping("/deleteUser/{id}")
    public Result deleteUserById(@ApiParam(value = "用户ID", required = true, name = "id") @PathVariable("id") String id) {
        boolean result = usersService.removeById(id);
        if (result) {
            return Result.OK();
        } else {
            return Result.Fail();
        }

    }

//    @RequestMapping("/pageListUsers/{current}/{limit}")
//    public Result pageListTeacher(@PathVariable("current")Integer current,@PathVariable("limit")Integer limit){
//        Page<Teacher> teacherPage = new Page<>(current,limit);
//        //-- 调用业务的分页查询方法
//        teacherService.page(teacherPage);
//        //-- 实际返回的只有总记录数和具体的数据集合
//        long total = teacherPage.getTotal();
//        List<Teacher> teacherList = teacherPage.getRecords();
//        System.out.println(teacherList);
//        return Result.ok().data("total",total).data("items",teacherList);
//    }

    /**
     * @param current
     * @param limit
     * @param userQuery
     * @return
     * @auth 曲哲
     */
    @ApiOperation(value = "根据条件分页查询用户")
    @PostMapping("/pageListUsers/{current}/{limit}")
    public Result pageListUserCondition(@ApiParam(value = "当前页码", name = "currentPage", required = true) @PathVariable("current") Integer current,
                                        @ApiParam(value = "每页显示数据条数", name = "pageSize", required = true) @PathVariable("limit") Integer limit,
                                        @ApiParam(value = "查询条件", name = "userQuery", required = true) @RequestBody(required = false) UserQuery userQuery) {

        Page<QUsers> usersPage = new Page<>(current, limit);
        //构建查询对象
        QueryWrapper<QUsers> wrapper = new QueryWrapper<>();
        System.out.println("用户条件"+userQuery.getRname());
        if (userQuery != null) {
            String rname = userQuery.getRname();
            if (!StringUtils.isEmpty(rname)) {
                wrapper.like("rname", rname);
            }
        }
        //按照更新时间进行降序排序保证没次都能查到最新更新时间
        wrapper.orderByDesc("gmt_modified");

        //分页查询的方法
        usersService.page(usersPage, wrapper);
//        usersService.page(usersPage,wrapper);

        //-- 实际返回的只有总记录数和具体的数据集合
        long total = usersPage.getTotal();

        List<QUsers> usersList = usersPage.getRecords();

        List<Users> userList = new ArrayList<>();
        for (QUsers qUsers : usersList) {
            Users users1 = this.newUser(qUsers);
            userList.add(users1);

        }
//        System.out.println("没封装的对象"+usersList.toString());
        System.out.println(userList);
        return Result.OK().data("total", total).data("items", userList);
    }

    @ApiModelProperty("将用户原始信息封装成一个新的用户")
    public Users newUser(QUsers qUsers) {
        Dictionary position = dictionaryService.getById(qUsers.getPostid());
        //            获取用户的部门编号 和名称
        Dictionary department = dictionaryService.getById(position.getPid());
        Users users1 = new Users();
        users1.setAddress(qUsers.getAddress());
        users1.setLname(qUsers.getLname());
        users1.setId(qUsers.getId());
        users1.setLpass(qUsers.getLpass());
        users1.setRname(qUsers.getRname());
        users1.setAge(qUsers.getAge());
        users1.setPhone(qUsers.getPhone());
        users1.setDepartment(department.getText());
        users1.setPosition(position.getText());
        users1.setBirthday(qUsers.getBirthday());
        users1.setGender(qUsers.getGender());
        users1.setCard(qUsers.getCard());
        users1.setEntrytime(qUsers.getEntrytime());
        users1.setIsdisable(qUsers.getIsdisable() == 1 ? "启用" : "禁用");
        users1.setVersion(qUsers.getVersion());
        users1.setGmtCreate(qUsers.getGmtCreate());
        users1.setGmtModified(qUsers.getGmtModified());
        return users1;
    }

    @ApiModelProperty("查询出部门")
    @PostMapping("/getDepartment")
//    根据pid查询出上级为部门的部门
    public Result getDepartment() {
        List<Dictionary> pid = dictionaryService.getPid(1);
        return Result.OK().data("items", pid);
    }

    @ApiModelProperty("根据部门id查询职位")
    @PostMapping("/getPosition/{pid}")
    public Result getPosition(@ApiParam(value = "部门id", name = "pid", required = true) @PathVariable("pid") Integer pid) {
        List<Dictionary> Position = dictionaryService.getPid(pid);
        return Result.OK().data("items", Position);
    }


    @ApiModelProperty(value = "添加用户")
    @PostMapping("/addUser")
    public Result addRole(@RequestBody QUsers users) {
        users.setLpass(MD5Util.md5Encrypt32Lower(users.getLpass()));
        System.out.println("用户" + users);
        boolean result = usersService.save(users);
        if (result) {
            return Result.OK();
        }

        return Result.Fail();
    }


    @ApiModelProperty("根据用户id删除")
    @GetMapping("/removeUser/{id}")
    public Result deleteTeacherById(@ApiParam(value = "用户ID", required = true, name = "id") @PathVariable("id") ArrayList<String> id) {
//        System.out.println(Arrays.toString(id));
        boolean result = usersService.removeByIds(id);
        if (result) {
            return Result.OK();
        }

        return Result.Fail();
    }

    @GetMapping("/initPassword/{id}")
    @ApiModelProperty("根据用户id重置用户密码")
    public Result initPassword(@ApiParam(value = "用户ID", required = true, name = "id") @PathVariable("id") String id) {
        System.out.println(id);
        boolean b = usersService.initPwdById(id);
        if (b) {
            return Result.OK();
        }
        return Result.Fail();
    }

    @GetMapping("/findByIdUser/{id}")
    @ApiModelProperty("按照用户id查询用户")
    public Result findByIdUser(@ApiParam(value = "用户ID", required = true, name = "id") @PathVariable("id") String id) {
        QUsers user = usersService.getById(id);
        Users users = this.newUser(user);
        if (users != null) {
            Result result = Result.OK();
            result.data("updateUser", users);
            return result;
        }
        return Result.Fail();
    }

    @PostMapping("/upUser")
    @ApiOperation(value = "修改用户")
    public Result updateTeacher(@RequestBody Users users) {
        try {

            String isdisable = users.getIsdisable();
            if ("启用".equals(isdisable)) {
                users.setIsdisable("1");
            } else {
                users.setIsdisable("0");
            }
            QUsers users1 = new QUsers();
            users1.setAddress(users.getAddress());
            users1.setLname(users.getLname());
            users1.setId(users.getId());
            users1.setLpass(users.getLpass());
            users1.setRname(users.getRname());
            users1.setAge(users.getAge());
            users1.setPhone(users.getPhone());

            try {
                users1.setDid(Integer.parseInt(users.getDepartment()));
            } catch (NumberFormatException e) {
                Dictionary finddept = dictionaryService.finddept(users.getDepartment());
                System.out.println(finddept);
                users1.setDid(finddept.getId());
            }
            try {
                users1.setPostid(Integer.parseInt(users.getPosition()));
            } catch (NumberFormatException e) {
                Dictionary finddept = dictionaryService.finddept(users.getPosition());
                users1.setPostid(finddept.getId());
            }
            users1.setBirthday(users.getBirthday());
            users1.setGender(users.getGender());
            users1.setCard(users.getCard());
            users1.setEntrytime(users.getEntrytime());
            users1.setIsdisable(users.getIsdisable().equals("启用") ? 1 : 0);
            users1.setVersion(users.getVersion());
            users1.setGmtCreate(users.getGmtCreate());
            users1.setGmtModified(users.getGmtModified());
            boolean result = usersService.updateById(users1);
            if (result)
                return Result.OK();
        } catch (Exception e) {
            return Result.Fail();
        }
        return Result.Fail();
    }
}
